package com.hust.util;

import com.hust.dao.PriceDao;
import com.hust.domain.Subscribe;
import com.hust.service.SubscribeService;
import com.hust.service.priceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

@Configuration
@EnableScheduling
public class ScheduUtils {

    @Autowired
    private SubscribeService subscribeService;

    @Autowired
    private priceService priceService;

    @Autowired
    private MailUtil mailUtil;

    private double calDiscount(int subPrice,int newPrice){
        return ((subPrice-newPrice)/(subPrice*1.0))*100.0;
    }

    //定时器每隔10秒执行
    @Scheduled(cron = "0 15 10 * * ?")
    //@Scheduled(cron = "0/10 * * * * ?")
    private void checkPrice(){
        //订阅后每隔十秒扫描所有的订阅信息，每扫描一条订阅信息，然后取出cid，根据cid去price表中查询最新价格，
        //与当前订阅的价格进行比较，如果跌幅超过20%，则发送邮件，告知降价了多少，邮件中同时包含了商品的url提醒用户
        //前去购买
        List<Subscribe> subscribes = subscribeService.scanAllSubscribes();
        if(subscribes!=null||subscribes.size()!=0){
            for (Subscribe subscribe : subscribes) {
                //取出订阅时的价格
                int subPrice = Integer.parseInt(subscribe.getSubPrice());
                //获取最新的价格
                String newPrice = priceService.getNewPrice(subscribe.getcId());
                int int_newPrice=Integer.parseInt(newPrice);
                //对比价格如果跌幅超过20%，调用JavaMail发送邮件
                if(calDiscount(subPrice,int_newPrice)>=20.0){
                    //调用邮件接口发送邮件,主题为"Notice of price reduction"，正文内容为打折金额，降幅以及商品url
                    String text="您好，您订阅的商品正在打折，狂减"+(subPrice-int_newPrice)+"元，打折力度"+calDiscount(subPrice,int_newPrice)+"速来购买<a href=\"www.baidu.com\"/a>";
                    mailUtil.sendDiscountMsg(text,"Notice of price reduction",subscribe.getuId().toString()+"@qq.com");
                }
            }
        }
    }
}
